package com.dsit.sq;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.dsit.sq.mydefineview.LongColorfulProgressBar;
import com.dsit.sq.mydefineview.PullToRefreshBase;
import com.dsit.sq.mydefineview.PullToRefreshScrollView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

/**
 * Created by dsit_dev04 on 2016/10/9.
 */
public class FuelBatteryActivity extends BaseActivity implements OnClickListener {
    private ImageView fuelReturnImageView;
    private TextView powerDataTextView;
    private TextView powerStatusTextView;
    private TextView dianliuDataTextView;
    private TextView dianliuStatusTextView;
    private TextView voltageDataTextView;
    private TextView voltageStatusTextView;
    private TextView fuelBatteryTextOne;
    private TextView fuelBatteryTextTwo;
    private TextView fuelBatteryTextThree;
    private TextView fuelBatteryVolTextOne;
    private TextView fuelBatteryVolTextTwo;
    private TextView fuelBatteryVolTextThree;
    private LongColorfulProgressBar fuelBatteryPowerProgressBar;
    private LongColorfulProgressBar voltageProgressBar;
    private LongColorfulProgressBar dianliuProgressBar;

    private PullToRefreshScrollView pullFuelBatteryScrollView;
    private LinearLayout fuelBatteryLinearLayout;
    private ScrollView fuelBatteryScrollView;
    private final int fuel_power = 4; // 燃料功率
    private final int fuel_voltage = 5;// 燃料电压
    private final int fuel_current = 6;// 燃料电流

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fuel_battery);
        fuelReturnImageView = (ImageView) findViewById(R.id.fuel_return_button);
        fuelReturnImageView.setOnClickListener(this);
        ProtoMsgDispatcher.getInstance().addDataListener(dataListener);


        LayoutInflater inflater = LayoutInflater.from(getApplication());
        fuelBatteryLinearLayout =(LinearLayout) inflater.inflate(R.layout.fuel_battery_layout,null);
        fuelBatteryTextOne = (TextView) fuelBatteryLinearLayout.findViewById(R.id.fuel_battery_textone);
        fuelBatteryTextTwo = (TextView) fuelBatteryLinearLayout.findViewById(R.id.fuel_battery_texttwo);
        fuelBatteryTextThree = (TextView) fuelBatteryLinearLayout.findViewById(R.id.fuel_battery_texthree);
        fuelBatteryTextOne.setText("0A");
        fuelBatteryTextTwo.setText("255A");
        fuelBatteryTextThree.setText("510A");
        fuelBatteryVolTextOne = (TextView) fuelBatteryLinearLayout.findViewById(R.id.fuel_battery_vol_textone);
        fuelBatteryVolTextTwo = (TextView) fuelBatteryLinearLayout.findViewById(R.id.fuel_battery_vol_texttwo);
        fuelBatteryVolTextThree = (TextView) fuelBatteryLinearLayout.findViewById(R.id.fuel_battery_vol_texthree);
        fuelBatteryVolTextOne.setText("0V");
        fuelBatteryVolTextTwo.setText("255V");
        fuelBatteryVolTextThree.setText("510V");

        powerDataTextView = (TextView) fuelBatteryLinearLayout.findViewById(R.id.power_data_text);
        powerStatusTextView = (TextView) fuelBatteryLinearLayout.findViewById(R.id.power_status_text);
        voltageDataTextView = (TextView) fuelBatteryLinearLayout.findViewById(R.id.voltage_data_text);
        voltageStatusTextView = (TextView) fuelBatteryLinearLayout.findViewById(R.id.voltage_status_text);
        dianliuDataTextView = (TextView) fuelBatteryLinearLayout.findViewById(R.id.dianliu_data_text);
        dianliuStatusTextView = (TextView) fuelBatteryLinearLayout.findViewById(R.id.dianliu_status_text);
        fuelBatteryPowerProgressBar = (LongColorfulProgressBar) fuelBatteryLinearLayout.findViewById(R.id.fuel_battery_power_progress);

        voltageProgressBar = (LongColorfulProgressBar) fuelBatteryLinearLayout.findViewById(R.id.voltage_status_image);
        dianliuProgressBar = (LongColorfulProgressBar) fuelBatteryLinearLayout.findViewById(R.id.dianliu_status_image);

        pullFuelBatteryScrollView = (PullToRefreshScrollView)findViewById(R.id.fuel_battery_pullscroll);
        pullFuelBatteryScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                new GetDataTask().execute();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {

            }
        });
        fuelBatteryScrollView = pullFuelBatteryScrollView.getRefreshableView();
        fuelBatteryScrollView.setVerticalScrollBarEnabled(false);
        fuelBatteryScrollView.addView(fuelBatteryLinearLayout);
//        powerBatteryScrollView.addView(createTextView());
        setLastUpdateTime();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ProtoMsgDispatcher.getInstance().removeDataListener(dataListener);
    }

    private class GetDataTask extends AsyncTask<Void, Void, String[]> {

        @Override
        protected String[] doInBackground(Void... params) {
            // Simulates a background job.
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String[] result) {
            pullFuelBatteryScrollView.onPullDownRefreshComplete();
            setLastUpdateTime();
            super.onPostExecute(result);
        }
    }
    private void setLastUpdateTime() {
        String text = formatDateTime(System.currentTimeMillis());
        pullFuelBatteryScrollView.setLastUpdatedLabel(text);
    }

    private SimpleDateFormat mDateFormat = new SimpleDateFormat("HH:mm:ss");
    private String formatDateTime(long time) {
        if (0 == time) {
            return "";
        }

        return mDateFormat.format(new Date(time));
    }

    //    private TextView createTextView() {
//        TextView textView = new TextView(this);
//
//        StringBuilder sb = new StringBuilder();
//        for (int i = 1; i < 200; ++i) {
//            sb.append(String.format(" %03d", i)).append("\n");
//        }
//
//        textView.setText(sb.toString());
//        textView.setTextColor(Color.WHITE);
//        textView.setTextColor(Color.BLACK);
//        textView.setTextSize(18);
//
//        return textView;
//    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fuel_return_button:
                finish();
            default:
                break;
        }
    }

    private DataListener dataListener = new DataListener() {
        @Override
        public void onUpdateData(ProtoMessage msg) {
            if(msg.getActionId().equals("canbus.msg")){
                byte[] data = msg.getContentData();
                Log.i("main_activity", "收到回调");
                String str = new String(data, 0, data.length);
                try {
                    JSONArray array = new JSONArray(str);
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject object = (JSONObject) array.get(i);
                        int id = object.getInt("id");
                        Double value = object.getDouble("value");
                        Bundle bundle = new Bundle();
                        Message message = new Message();
                        message.setData(bundle);
                        bundle.putDouble("value", value);
                        switch (id) {
                            case fuel_power:
                                message.what = fuel_power;
                                mHandler.sendMessage(message);
                                break;
                            case fuel_voltage:
                                message.what = fuel_voltage;
                                mHandler.sendMessage(message);
                                break;
                            case fuel_current:
                                message.what = fuel_current;
                                mHandler.sendMessage(message);
                                break;
                            default:
                                break;
                        }
                        Log.i("data", object.toString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message message) {
            try {
                Bundle bundle = new Bundle();
                bundle = message.getData();
                switch (message.what) {
                    case fuel_power:
                        int progress1 = (int) ((float) (bundle.getDouble("value") / 80) * 100);
                        fuelBatteryPowerProgressBar.setProgress(progress1);
                        powerDataTextView.setText(formatDouble(bundle.getDouble("value")) + "kw");
                        powerStatusTextView.setText("");
                        break;
                    case fuel_voltage:
                        int progress2 = (int) ((float) (bundle.getDouble("value") / 510) * 100);
                        voltageProgressBar.setProgress(progress2);
                        voltageDataTextView.setText(formatDouble(bundle.getDouble("value")) + "V");
                        voltageStatusTextView.setText("");
                        break;
                    case fuel_current:
                        int progress3 = (int) ((float) (bundle.getDouble("value") / 510) * 100);
                        dianliuProgressBar.setProgress(progress3);
                        dianliuDataTextView.setText(formatDouble(bundle.getDouble("value")) + "A");
                        dianliuStatusTextView.setText("");
                        break;
                    default:
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private String formatDouble(Double data) {
        DecimalFormat format = new DecimalFormat("0.00");
        return format.format(data);
    }
}
